package com.example.taobaounion.ui.fragment;

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;
import com.example.taobaounion.model.bean.Categories;
import com.example.taobaounion.model.bean.HomePagerContent;
import com.example.taobaounion.model.bean.IBaseInfo;
import com.example.taobaounion.presenter.ICategoryPagerPresenter;
import com.example.taobaounion.ui.adapter.LinearItemContentAdapter;
import com.example.taobaounion.ui.adapter.LooperPagerAdapter;
import com.example.taobaounion.ui.custom.AutoLoopViewPager;
import com.example.taobaounion.utils.Constants;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.PresenterManager;
import com.example.taobaounion.utils.SizeUtils;
import com.example.taobaounion.utils.TicketUtils;
import com.example.taobaounion.utils.ToastUtil;
import com.example.taobaounion.view.ICategoryPagerCallback;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.Views.TbNestedScrollView;

import java.util.List;

import butterknife.BindView;

public class HomePagerFragment extends BaseFragment implements ICategoryPagerCallback, LinearItemContentAdapter.OnItemClickListener, LooperPagerAdapter.OnLooperPageItemClickListener {

    private ICategoryPagerPresenter mCategoryPagePresenter;
    private int mMaterialID;

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;
    @BindView(R.id.looper_pager)
    public AutoLoopViewPager looperPager;
    @BindView(R.id.home_pager_title)
    public TextView currentCategoryTitleTv;
    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;
    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout mTwinklingRefreshLayout;
    @BindView(R.id.home_pager_parent)
    public LinearLayout homePagerParent;
    @BindView(R.id.home_pager_nested_scroller)
    public TbNestedScrollView homePagerNestedView;
    @BindView(R.id.home_pager_header_container)
    public LinearLayout homeHeaderContainer;
    private LinearItemContentAdapter mContentAdapter;
    private LooperPagerAdapter mLooperPagerAdapter;

    public static HomePagerFragment newInstance(Categories.DataBean category){
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        //保存数据在homePagerFragment里面(这样的原因是每当你点击分类TapLayout时都能拿到他的id和title)
        Bundle bundle=new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE,category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID,category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        //可见的时候去调用开始轮播
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        //不可见的时候暂停
        looperPager.stopLoop();
    }

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }

    @Override
    protected void initView(View rootView) {
        //设置布局管理器
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull  Rect outRect, @NonNull  View view, @NonNull  RecyclerView parent, @NonNull  RecyclerView.State state) {
                outRect.top=8;
                outRect.bottom=8;
            }
        });
        //创建适配器
        mContentAdapter = new LinearItemContentAdapter();
        //设置适配器
        mContentList.setAdapter(mContentAdapter);
        //创建轮播图适配器
        mLooperPagerAdapter = new LooperPagerAdapter();
        //设置适配器
        looperPager.setAdapter(mLooperPagerAdapter);
        //设置Refresh相关属性
        mTwinklingRefreshLayout.setEnableRefresh(false);//不让他上拉刷新
        mTwinklingRefreshLayout.setEnableLoadmore(true);//让他下拉加载更多
    }

    @Override
    protected void initPresenter() {
        mCategoryPagePresenter = PresenterManager.getInstance().getCategoryPagerPresenter();
        mCategoryPagePresenter.registerViewCallback(this);
    }

    @Override
    protected void loadData() {
        //没点击一个分类TabLayout就执行fragment的onCreateView,执行到loadData,拿到前面newInstance中bundle保存的数据
        Bundle arguments = this.getArguments();
        String title = arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialID = arguments.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        //TODO：加载数据
        if(mCategoryPagePresenter!=null){
            mCategoryPagePresenter.getContentByCategoryId(mMaterialID);
        }
        if(currentCategoryTitleTv!=null){
            currentCategoryTitleTv.setText(title);
        }
    }

    @Override
    protected void initListener() {

        mContentAdapter.setOnItemClickListener(this);
        mLooperPagerAdapter.setOnLooperPageItemClickListener(this);

        //因为布局中引用了NestedScrollView的缘故，会多次调用OnCreateView重复创建InnerHolder，造成内存消耗
        //所以我们对recyclerView进行相应的设置
        //当布局发生变化时
        homePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(homeHeaderContainer==null){
                    return;
                }
                int headerHeight = homeHeaderContainer.getMeasuredHeight();
                //LogUtils.d(HomePagerFragment.this,"headerHeight---->"+headerHeight);
                 homePagerNestedView.setHeaderHeight(headerHeight);
                int measuredHeight = homePagerParent.getMeasuredHeight();
                //LogUtils.d(HomePagerFragment.this,"measuredHeight.....--->"+measuredHeight);
                LinearLayout.LayoutParams layoutParams =(LinearLayout.LayoutParams)mContentList.getLayoutParams();
               layoutParams.height=measuredHeight;
               mContentList.setLayoutParams(layoutParams);
               // LogUtils.d(HomePagerFragment.this,"measuredHeight.....--->"+layoutParams.height);
                 //当不是0后就不进来，避免频繁调用onGlobalLayout
                if(measuredHeight!=0){
                     homePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                 }
            }
        });


        looperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //滑动时
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            //选中时也就是停下时
            @Override
            public void onPageSelected(int position) {
                //如果不加这个判断的话可能会响应数据和更新不同步，就是说数据还没有到，却更新UI
                //加个判断即可，如果是0的话无意义，直接返回。(等到数据回来的时候再执行)
                //如果之前已经预加载的话即使是0也不会切换指示器因为他之前已经加载过了，可以不用，但是如果之前没有预加载
                //再是0的话，则会再次执行到getDataSize()数据回来。
                //因为这个是每当页面选中的时候都会执行，不只是执行一次，当为0的时候没意义直接返回即可
                if(mLooperPagerAdapter.getDataSize()==0){
                    return;
                }
                int targetPosition=position % mLooperPagerAdapter.getDataSize();
                //切换指示器
                updateLooperIndicator(targetPosition);
            }

            //滑动状态发生改变时（手离开惯性那个）
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //因为之前上拉刷新false了,下拉加载更多true所以使用onLoadMore
        mTwinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                LogUtils.d(HomePagerFragment.this,"触发了loader more...");
//                mTwinklingRefreshLayout.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mTwinklingRefreshLayout.finishLoadmore();
//                        Toast.makeText(getContext(),"加载了100条数据",Toast.LENGTH_SHORT).show();
//                    }
//                },3000);
                //去加载更多内容
                if(mCategoryPagePresenter!=null){
                    LogUtils.d(HomePagerFragment.this,"mMaterialID--->"+mMaterialID);
                    mCategoryPagePresenter.loaderMore(mMaterialID);
                }
            }
        });
    }

    private void updateLooperIndicator(int targetPosition) {
        //LogUtils.d(HomePagerFragment.this,"执行到了指示器");
        for (int i=0;i<looperPointContainer.getChildCount();i++){
            View point = looperPointContainer.getChildAt(i);
            if(i==targetPosition){
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            }else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
        }
    }

    @Override
    public void onContentLoaded(List<HomePagerContent.DataBean> contents) {
        //数据列表加载到了
        //更新UI
        mContentAdapter.setData(contents);
        //加载成功页面
        setUpState(State.SUCCESS);
    }

    //UI层知道自己的id
    @Override
    public int getCategoryId() {
        return mMaterialID;
    }

    @Override
    public void onLoading() {
      setUpState(State.LOADING);
    }

    @Override
    public void onError() {
        //网络错误
        setUpState(State.ERROR);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    public void onLoaderMoreError() {
        if(mTwinklingRefreshLayout!=null){
            mTwinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.showToast("网络异常，请稍后重试");

    }

    @Override
    public void onLoadMoreEmpty() {
        if(mTwinklingRefreshLayout!=null){
            mTwinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.showToast("没有更多商品");

    }

    @Override
    public void onLoaderMoreLoaded(List<HomePagerContent.DataBean> contents) {
         //添加到设配器数据的底部
        mContentAdapter.addData(contents);
        //添加完后结束加载更多
        if(mTwinklingRefreshLayout!=null){
            mTwinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.showToast("加载了"+contents.size()+"条数据");

    }

    //加载轮播图
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onLooperListLoaded(List<HomePagerContent.DataBean> contents) {
       //LogUtils.d(this,"Looper size--->"+contents.size());
        mLooperPagerAdapter.setData(contents);
        looperPointContainer.removeAllViews();
        //处理一下(将第一个数据的图片显示到当前轮播图)
        int dx=(Integer.MAX_VALUE/2)%contents.size();
        int targetCenterPosition=(Integer.MAX_VALUE/2)-dx;
        //设置到中间点
        looperPager.setCurrentItem(targetCenterPosition);
        //LogUtils.d(this,"utl--->"+contents.get(0).getPict_url());

        //添加点
        for(int i=0;i<contents.size();i++){
            View point = new View(getContext());
            int size = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.leftMargin=SizeUtils.dip2px(getContext(),5);
            layoutParams.rightMargin=SizeUtils.dip2px(getContext(),5);
            point.setLayoutParams(layoutParams);
            if(i==0){
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
                //LogUtils.d(this,"点击到i==0了");
            }else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
            looperPointContainer.addView(point);
        }
    }

    @Override
    protected void release() {
        if(mCategoryPagePresenter!=null){
            mCategoryPagePresenter.unregisterViewCallback(this);
        }
    }

    @Override
    protected void onRetryClick() {
        if(mCategoryPagePresenter!=null){
            mCategoryPagePresenter.getContentByCategoryId(mMaterialID);
        }
    }

    @Override
    public void onItemClick(IBaseInfo item) {
        //列表内容被点击了
        LogUtils.d(this,"item click---->"+item.getTitle());
        handleItemClick(item);
    }

    private void handleItemClick(IBaseInfo item) {
        TicketUtils.toTicketPage(getContext(),item);
    }

    @Override
    public void onLooperItemClick(IBaseInfo item) {
        //轮播图内容被点击了
        LogUtils.d(this,"looper item click---->"+item.getTitle());
        handleItemClick(item);
    }
}
